import { _decorator, Component, Node, UITransform, tween, Layout, Prefab, instantiate } from 'cc';
import { GetPlayerGoodsVoAPI, PlayerGoodsVo } from '../../../GameAPI';
import { CardController } from './CardController';
const { ccclass, property } = _decorator;

@ccclass('CardsController')
export class CardsController extends Component {


    //是否超出
    isExceed:boolean = false;
    cards:CardController[] = [];

    //操作是否在Cards中
    isLeave:boolean = false;

    async start() {

        this.updateCards();

    }
    

    //更新卡牌
    updateCards(){
        
        this.cards = this.getComponentsInChildren(CardController);

        let totalHeight = 0;

        this.cards.forEach(card => {
            let ui = card.getComponent(UITransform);
            totalHeight += ui.height;
        })

        let ui = this.node.getComponent(UITransform);

        //如果超出则叠着
        if(totalHeight > ui.height){

            this.isExceed = true;

            let lastHeight = this.cards[this.cards.length - 1].getComponent(UITransform).height;
            let addh = (ui.height - lastHeight) / (this.cards.length - 1);
            let h = 0;
            
            this.cards.forEach((card,index) => {
    
                card.index = index;
                card.cards = this;
    
                Object.assign(card.defaultPos,{
                    x:0,
                    y:-h
                });
                
                h += addh;
    
            })

        }else{

            this.isExceed = false;

            let addh = 0;

            this.cards.forEach((card,index) => {
    
                card.index = index;
                card.cards = this;

                let cui = card.getComponent(UITransform);

                Object.assign(card.defaultPos,{
                    x:0,
                    y:-addh
                });
                
                addh += cui.height;
    
            })

        }

        

    }

    //展开卡
    openCard(index){

        if(this.isExceed){

            this.updateCards();
            
            let ui = this.node.getComponent(UITransform);
            let lastHeight = this.cards[this.cards.length - 1].getComponent(UITransform).height;
            let addh = (ui.height - lastHeight) / (this.cards.length - 1);

            let h = this.cards[index].getComponent(UITransform).height;

            //打开卡牌
            for (let i = index+1; i < this.cards.length; i++) {

                Object.assign(this.cards[i].defaultPos,{
                    x:0,
                    y:this.cards[i].defaultPos.y - (h - addh)
                })

            }

        }

    }

    //添加卡牌
    addCard(card:CardController){

        this.node.addChild(card.node);
        this.updateCards();

    }

    update(deltaTime: number) {
        
    }

}

